package com.example.module.iot.emq.util;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

@Slf4j
public class EmqxUtils {

    private static MqttClient mqttClient;

    @Resource
    public void setMqttClient(MqttClient mqttClient) {
        EmqxUtils.mqttClient = mqttClient;
    }

    public static void publish(String topic, String message) {
        // 创建消息并设置 QoS
        MqttMessage mqttMessage = new MqttMessage(message.getBytes());
        int qos = 0;
        mqttMessage.setQos(qos);
        // 发布消息
        try {
            mqttClient.publish(topic, mqttMessage);
//            mqttClient.getTopic(topic).publish(mqttMessage);
            log.info("Message published, topic: {}, content: {}", topic, message);
        } catch (MqttException e) {
            log.error("MQTT发送消息失败，e: {}", e.getMessage());
        }
    }
}
